﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.ESS.APP.App_UI.Forms;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;
using KPIS.GERP.ESS.DAL;
//using KPIS.GERP.ESS.IBLL;
//using KPIS.GERP.ESS.BLL;
//using KPIS.GERP.ESS.MODEL;
using _WebShared.Classes;
using Telerik.Web.UI;
using System.Linq;
using KPIS.DBM;

namespace KPIS.GERP.ESS.APP.App_UI.UserControls
{
    public partial class Mail_Request : System.Web.UI.UserControl
    {
        Main main = new Main();
        ESS.BLL.B_MessageSend send = new ESS.BLL.B_MessageSend();
        ESS.BLL.B_MessageReply reply = new ESS.BLL.B_MessageReply();
        FIM_Employees.FIM_Employees emp = new FIM_Employees.FIM_Employees();
        FIM_MoneyRequests.FIM_MoneyRequests mr = new FIM_MoneyRequests.FIM_MoneyRequests();
        FIM_MoneyRequestDtls.FIM_MoneyRequestDtls mrd = new FIM_MoneyRequestDtls.FIM_MoneyRequestDtls();
        //FIM_MoneyRequestTravelers.FIM_MoneyRequestTravelers mrTrav = new FIM_MoneyRequestTravelers.FIM_MoneyRequestTravelers();
        FIM_MAS_BankAccounts.FIM_MAS_BankAccounts bank = new FIM_MAS_BankAccounts.FIM_MAS_BankAccounts();
        FIM_Cheques.FIM_Cheques cheque = new FIM_Cheques.FIM_Cheques();
        FIM_ChequeBooks.FIM_ChequeBooks chequeBook = new FIM_ChequeBooks.FIM_ChequeBooks();
        FIM_Payments.FIM_Payments pay = new FIM_Payments.FIM_Payments();
        FIM_PaymentCheques.FIM_PaymentCheques payCheque = new FIM_PaymentCheques.FIM_PaymentCheques();
        BGM_ProjectOperationReport.BGM_ProjectOperationReport opRpt = new BGM_ProjectOperationReport.BGM_ProjectOperationReport();
        B_HrmEmployees emplist = new B_HrmEmployees();
        D_HrmPositions pos = new D_HrmPositions();
        B_SECURITY_Users user = new B_SECURITY_Users();
        D_ACM_GENERATE_ACCOUNT_Auto acc = new D_ACM_GENERATE_ACCOUNT_Auto();
        DBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void LoadData(string strSendSeq, FIM_MoneyRequests.M_FIM_MoneyRequests info, bool bEdit
            , string strApprovePathSeq, string strStatus, string strSender)
        {
            lblSendSeq.Text = strSendSeq;
            lblApprovePathSeq.Text = strApprovePathSeq;
            FIM_Employees.M_HRM_PS_Employees EmpInfo = emp.GetInfo(info.emp_seq.ToString());
            lblSendSeq.Text = strSendSeq;
            lblMoneyReqSeq.Text = info.money_req_seq.ToString();
            lblEmpSeq.Text = info.emp_seq.ToString();
            lblSendDate.Text = "เมื่อวันที่   " + info.money_req_date.Value.ToShortDateString();
            lblEmpName.Text = info.emp_name;
            lblPosName.Text = EmpInfo.pos_name;
            lblPosRefNo.Text = EmpInfo.pos_ref;
            lblJobsiteName.Text = EmpInfo.working_job_site_name;
            lblMoneyReqName.Text = info.money_req_name;
            lblcontact_seq.Text = info.contact_name;
            lblEmpInternal.Text = info.doc_ref_no;
            lblEmpExternal.Text = info.doc_ref_no;
            rblUseAdvance.Items[0].Text = info.bgm_source_name;
            rblUseAdvance.SelectedValue = info.use_advance;
            lblBgmSourceSeq.Text = info.bgm_source_seq.ToString();
            lblBgmSourceName.Text = (info.use_advance == "1" ? "เงินทดรองราชการ" : info.bgm_source_name);
            lblBgmExpGrpName.Text = info.bgm_exp_grp_name;
            lblRemarks.Text = info.remarks;
            SetEditBgmSource(false);
            lblBgmYear.Text = info.bgm_year.ToString();
            lblEventSeq.Text = info.event_seq.ToString();
            lblDnSeq.Text = info.icm_dn_seq.ToString();
            lblDnRefNo.Text = info.dn_ref_no;
            lblMoneyReqRefNo.Text = info.ref_no;
            lblMoneyReqDate.Text = info.money_req_date.Value.ToShortDateString();

            lblNoAccount.Visible = info.use_advance == "1";
            ul1.Visible = info.use_advance != "1";
            ul2.Visible = info.use_advance != "1";

            if (info.use_advance == "1")
            {
                //PanelPayment.Visible = true;
                //LoadPaymentInfo();
            }

            if (info.contact_seq == null)
            {
                PanelContact.Visible = false;
                PanelEmp.Visible = true;
            }
            else
            {
                PanelContact.Visible = true;
                PanelEmp.Visible = false;
            }
            LoadFinMoneyReqDtls();
            //IList<FIM_MoneyRequestTravelers.M_FIM_MoneyRequestTravelers> personInfoList = mrTrav.GetFull(lblMoneyReqSeq.Text);
            //Repeater3.DataSource = personInfoList;
            //Repeater3.DataBind();
            LoadSenderInfo(info.emp_seq.ToString());

            if (lblEventSeq.Text != "16")
            {
                LoadRepeaterAccount();
            }

            bool bEnable = strStatus == "2";
            cmdApprove.Enabled = !bEnable && bEdit;
            cmdForword.Enabled = !bEnable && bEdit;
            cmdSendBack.Enabled = !bEnable && bEdit;
            cmdEditBgmSource.Enabled = !bEnable && bEdit;
            PanelOption.Visible = true;
            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendTo2.Visible = false;
            PanelSendBack.Visible = false;
            PanelSend.Visible = false;
            txtRemark.Text = "";
            SetButton();
        }

        protected void SetButton()
        {
            int nStepNo = 1;
            string strNextStepNo = send.GetNextStepNo(lblApprovePathSeq.Text, lblFinSumAmount.Text);

            if (Int32.TryParse(strNextStepNo, out nStepNo))
            {
                if (nStepNo > 0)
                {
                    cmdApprove.Visible = false;
                    cmdForword.Visible = true;
                }
                else
                {
                    cmdApprove.Visible = true;
                    cmdForword.Visible = false;
                }
            }
        }

        protected void LoadApprover()
        {
            int nStepNo = 1;
            string strNextStepNo = send.GetNextStepNo(lblApprovePathSeq.Text, lblFinSumAmount.Text);

            if (Int32.TryParse(strNextStepNo, out nStepNo))
            {
                if (nStepNo > 0)
                {
                    cmdApprove.Visible = false;
                    cmdForword.Visible = true;

                    // Edit by Aek 2014-07-29
                    // Calculate base on to_emp_seq field in table message_send, not login session 
                    // Change to Money request Employee
                    var info = mr.GetInfo(lblMoneyReqSeq.Text);
                    DataTable dtb = send.GetCurrentApprover(info.emp_seq.ToString(), lblSendSeq.Text, "FIM_MONEY_REQUESTS", nStepNo);

                    if (dtb != null)
                    {
                        if (dtb.Rows.Count > 0)
                        {
                            lblNewApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
                            //ddlApprover.SelectedValue = dtb.Rows[0]["emp_seq"].ToString();
                            if (dtb.Rows[0]["approver_type"].ToString() != "3")
                            {
                                PanelSendTo.Visible = true;
                                PanelSendTo2.Visible = false;
                                lblApproverEmpSeq.Text = dtb.Rows[0]["emp_seq"].ToString();
                                lblApproverPosSeq.Text = dtb.Rows[0]["pos_seq"].ToString();
                                LoadEmpInfo(dtb.Rows[0]["emp_seq"].ToString(), dtb.Rows[0]["pos_seq"].ToString());
                            }
                            else
                            {
                                PanelSendTo.Visible = false;
                                PanelSendTo2.Visible = true;
                                lblPosGrpSeq.Text = dtb.Rows[0]["pos_grp_seq"].ToString();
                                lblPosGrpName.Text = dtb.Rows[0]["pos_grp_name"].ToString();
                                rptPosGrpDtls.DataSource = send.GetEmployeeInPositionGroup(dtb.Rows[0]["pos_grp_seq"].ToString());
                                rptPosGrpDtls.DataBind();
                            }
                        }
                    }
                }
                else
                {
                    cmdApprove.Visible = true;
                    cmdForword.Visible = false;
                }
            }
        }

        protected void LoadSenderInfo(string strEmpSeq)
        {
            DataTable dtb = emplist.GetInfo(Convert.ToInt32(strEmpSeq));

            if (dtb.Rows.Count > 0)
            {
                lblEmpSeq.Text = strEmpSeq;
                lblEmpName.Text = dtb.Rows[0]["full_name"].ToString();
                lblPosName.Text = dtb.Rows[0]["pos_name"].ToString();
                lblClassName.Text = dtb.Rows[0]["class_name"].ToString();
                lblJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();
            }
        }

        protected void LoadPaymentInfo()
        {
            string strMoneyReqSeq = lblMoneyReqSeq.Text;
            string strBgmSourceSeq = lblBgmSourceSeq.Text;
            FIM_Payments.M_FIM_Payments payInfo = pay.GetInfoFromMoneyReqSeq(strMoneyReqSeq);

            LoadDDLBankAccSeq(strBgmSourceSeq);

            if (payInfo.record_status != null)
            {
                lblPaySeq.Text = payInfo.pay_seq.ToString();
                IList<FIM_PaymentCheques.M_FIM_PaymentCheques> payChequeInfoList = payCheque.GetFull(lblPaySeq.Text, null);

                if (payChequeInfoList.Count > 0)
                {
                    ddlBankAccSeq.SelectedValue = payChequeInfoList[0].bank_acc_seq.ToString();
                    LoadDDLChequeBook();
                    ddlChequeBook.SelectedValue = payChequeInfoList[0].cheque_book_seq.ToString();
                    LoadDDLCheque();
                    ddlCheque.SelectedValue = payChequeInfoList[0].cheque_seq.ToString();
                }
            }
            else
            {
                LoadDDLChequeBook();
                LoadDDLCheque();
            }
        }

        protected void LoadDDLBankAccSeq(string strBgmSourceSeq)
        {
            ddlBankAccSeq.DataSource = bank.GetList("2", strBgmSourceSeq);
            ddlBankAccSeq.DataBind();
            main.InsertEmptyDDLSelect(ddlBankAccSeq);
            //if (ddlBankAccSeq.Items.Count > 0)
            //{
            //    ddlBankAccSeq.SelectedIndex = 0;
            //    LoadDDLChequeBook();
            //}
        }

        protected void LoadDDLChequeBook()
        {
            if (ddlBankAccSeq.SelectedValue.Length > 0)
            {
                ddlChequeBook.DataSource = chequeBook.GetList(ddlBankAccSeq.SelectedValue, "1");
            }
            else
            {
                ddlChequeBook.DataSource = null;
            }

            ddlChequeBook.DataBind();
            main.InsertEmptyDDLSelect(ddlChequeBook);
            //if (ddlChequeBook.Items.Count > 0)
            //{
            //    ddlChequeBook.SelectedIndex = 0;
            //    LoadDDLCheque();
            //}
        }

        protected void LoadDDLCheque()
        {
            if (ddlChequeBook.SelectedValue.Length > 0)
            {
                ddlCheque.DataSource = cheque.GetList(null, null, ddlChequeBook.SelectedValue, "1");
            }
            else
            {
                ddlCheque.DataSource = null;
            }

            ddlCheque.DataBind();
            main.InsertEmptyDDLSelect(ddlCheque);
        }

        public void cmdApprove_Click(object sender, EventArgs e)
        {
            //string strNextSeqNo = send.GetNextStepNo(lblApprovePathSeq.Text);

            //if (strNextSeqNo == "0")
            //{
            //    PanelApprove.Visible = true;
            //    PanelSendTo.Visible = false;
            //    lblMode.Text = "A";
            //}
            //else
            //{
            //    DataTable dtb = send.GetCurrentApprover(Session["EmpSeq"].ToString(), "bgm_project_operation"
            //        , Convert.ToInt32(strNextSeqNo));

            //    if (dtb != null)
            //    {
            //        if (dtb.Rows.Count > 0)
            //        {
            //            lblNewApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
            //            LoadEmpInfo(dtb.Rows[0]["emp_seq"].ToString());
            //        }
            //    }

            //    PanelApprove.Visible = false;
            //    PanelSendTo.Visible = true;
            //    lblMode.Text = "F";
            //}

            PanelApprove.Visible = true;
            PanelSendTo.Visible = false;
            PanelSendTo2.Visible = false;
            lblMode.Text = "A";

            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;
        }

        protected void cmdForword_Click(object sender, EventArgs e)
        {
            LoadApprover();
            PanelApprove.Visible = false;
            //PanelSendTo.Visible = true;
            //PanelSendTo2.Visible = false;
            lblMode.Text = "F";

            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;
        }

        protected void cmdSendBack_Click(object sender, EventArgs e)
        {
            lblMode.Text = "B";

            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendTo2.Visible = false;
            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;
            lblError.Text = "";
        }

        protected void LoadEmpInfo(string strEmpSeq, string strPosSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                DataTable dtb = emplist.GetInfo(Convert.ToInt32(strEmpSeq));

                lblApproverEmpSeq.Text = strEmpSeq;
                lblApproverPosSeq.Text = strPosSeq;// dtb.Rows[0]["t_pos_seq"].ToString();
                ddlApprover.Text = dtb.Rows[0]["full_name"].ToString();
                lblApproverClassName.Text = dtb.Rows[0]["class_name"].ToString();
                lblApproverExecPosName.Text = dtb.Rows[0]["exec_pos_name"].ToString();
                lblApproverJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();

                if (!string.IsNullOrEmpty(strPosSeq) && dtb.Rows[0]["t_pos_seq"].ToString() != strPosSeq)
                {
                    DataTable dtb2 = pos.GetPosition(strPosSeq);

                    lblApproverPosName.Text = "รักษาการณ์ตำแหน่ง " + dtb2.Rows[0]["pos_name"].ToString();
                }
                else
                {
                    lblApproverPosSeq.Text = dtb.Rows[0]["t_pos_seq"].ToString();
                    lblApproverPosName.Text = dtb.Rows[0]["pos_name"].ToString();
                }
            }
        }

        private bool directApprove = false;
        public string Approve(string remark)
        {
            directApprove = true;
            cmdApprove_Click(new Object(), new EventArgs());
            txtRemark.Text = remark;
            return cmdSendClick();
        }

        public string GetFiscalPeriod(DateTime dt)
        {
            string strFiscalPeriod = dt.Year.ToString() + "/" + dt.Month.ToString();

            return strFiscalPeriod;
        }
        public void cmdSend_Click(object sender, EventArgs e)
        {
            cmdSendClick();
        }

        public string cmdSendClick()
        {
            string strSQL = "";
            int nEmpSeqLogin = SsMng.EmpSeqI;
            //BGM_ProjectOperation.M_BGM_ProjectOperation operInfo = new BGM_ProjectOperation.M_BGM_ProjectOperation();
            FIM_MoneyRequests.M_FIM_MoneyRequests mrInfo = new FIM_MoneyRequests.M_FIM_MoneyRequests();
            M_MessageSend info = new M_MessageSend();
            M_MessageReply replyInfo = new M_MessageReply();
            // By Aek 2014-07-29
            // remark: in forwarding FromEmpSeq should be the previous emp_seq in message_send
            // string strFromEmpSeq = Session["EmpSeq"].ToString();
            var messageSendPrev = send.GetFull(null, null, null, null, null, null, null, lblSendSeq.Text)[0];
            string strFromEmpSeq = messageSendPrev.to_emp_seq.ToString();
            string strFromPosSeq = messageSendPrev.to_pos_seq.ToString();
            string strMoneyReqSeq = lblMoneyReqSeq.Text;

            int nFromEmpSeq = SsMng.EmpSeqI;//Convert.ToInt32(strFromEmpSeq);
            int nFromPosSeq = SsMng.PosSeqI;//Convert.ToInt32(strFromPosSeq);

            Nullable<int> nToEmpSeq = null;
            Nullable<int> nToPosSeq = null;
            Nullable<int> nWodEmpSeq = nEmpSeqLogin == nFromEmpSeq ? (int?)null : nEmpSeqLogin;

            bool bLeaf = true;
            string strSendSeq = lblSendSeq.Text;
            string strToEmpSeq = lblApproverEmpSeq.Text;
            string strToPosSeq = lblApproverPosSeq.Text;

            if (strToEmpSeq.Length == 0 && ddlApprover.Visible)
            {
                lblError.Text = "คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง";
                return lblError.Text;
            }
            else
            {
                lblError.Text = "";
            }

            while (bLeaf)
            {
                ESS.MODEL.M_MessageSend sendInfo = send.GetInfo(strSendSeq);
                string strFromSendSeq = sendInfo.from_send_seq.ToString();

                if (string.IsNullOrEmpty(strFromSendSeq))
                {
                    bLeaf = false;
                    nToEmpSeq = sendInfo.from_emp_seq;
                    nToPosSeq = main.ConvertNullInt(strToPosSeq);//send.GetPosSeqFromEmpSeq(Convert.ToString(nToEmpSeq));
                }

                strSendSeq = strFromSendSeq;
            }

            switch (lblMode.Text)
            {
                case "A":
                    #region A
                    try
                    {
                        BGM_ProjectOperationExpense.BGM_ProjectOperationExpense oe = new BGM_ProjectOperationExpense.BGM_ProjectOperationExpense();
                        FIM_MoneyRequests.M_FIM_MoneyRequests mrInfo2 = mr.GetInfo(strMoneyReqSeq);
                        mrInfo.borrow_no = mrInfo2.event_seq == 16 ? mr.GenerateNextMoneyRequestBorrowNumber((mrInfo2.bgm_source_seq ?? 1) == 1 ? "1" : "2") : null;
                        mrInfo.money_req_seq = Convert.ToInt32(strMoneyReqSeq);
                        mrInfo.record_status = "A";
                        mrInfo.allow = "1";
                        mrInfo.updated_by = nEmpSeqLogin;
                        mrInfo.updated_when = DateTime.Now;

                        if (mrInfo2.record_status == "A")
                        {
                            main.MessageAlert(Page, "รายการนี้อนุมัติไปแล้ว กรุณาอย่ากดซ้ำ");
                            return "";
                        }

                        dbManager.Open();
                        dbManager.BeginTransaction();
                        dbManager.CreateParameters(2);

                        dbManager.AddParameters(0, "@money_req_seq", Convert.ToInt32(strMoneyReqSeq));
                        dbManager.AddParameters(1, "@delete_record_status", SystemInfo._DeleteRecordStatus);

                        strSQL = @"
select coalesce(rqd.amount, 0) as amount
, rq.bgm_proj_oper_seq, rq.bgm_source_seq, rq.bgm_exp_grp_seq
--, coalesce(allrpt.remain_amount, 0) - coalesce(rpt.cal_amount, 0) as remain_amount

from fim_money_requests rq
left join (select rqd.money_req_seq
    , sum(coalesce(rqd.amount, 0)) as amount
    from fim_money_request_dtls rqd
    where rqd.record_status not like @delete_record_status
    group by rqd.money_req_seq
) rqd on rq.money_req_seq = rqd.money_req_seq

--left join (select dni.DnId, sum(coalesce(rpt.cal_amount, 0)) as cal_amount
--from IcmDeliveryNoteItem dni
--left join IcmPurchaseOrderInstallmentItem poii on dni.PoInstallItemId = poii.PoInstallItemId
--left join IcmBidderQuotation quo on poii.BidderQuoId = quo.BidderQuoId
--left join IcmPurchaseRequestItem pri on quo.PrItemId = pri.PrItemId
--left join bgm_project_operation_report rpt on pri.PrItemId = rpt.icm_pr_item_seq
--where rpt.record_status <> 'D'
--group by dni.DnId
--) rpt on rq.icm_dn_seq = rpt.DnId

--left join (select ope.bgm_proj_oper_seq, pje.bgm_source_seq, sum(coalesce(rpt.cal_amount, 0)) as remain_amount
--from bgm_project_operation_expense ope
--left join bgm_project_expense pje on ope.bgm_proj_exp_seq = pje.bgm_proj_exp_seq
--left join bgm_project_operation_report rpt on ope.bgm_proj_oper_exp_seq = rpt.bgm_proj_oper_exp_seq
--where ope.record_status not like 'D'
--and rpt.record_status not like 'D'
--group by ope.bgm_proj_oper_seq, pje.bgm_source_seq
--) allrpt on rq.bgm_proj_oper_seq = allrpt.bgm_proj_oper_seq
--	and rq.bgm_source_seq = allrpt.bgm_source_seq

where rq.money_req_seq = @money_req_seq";

                        var dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                        for (int i = 0; i < dtb.Rows.Count; i++)
                        {
                            double dBathAmount = main.ConvertNullDouble(dtb.Rows[i]["amount"]) ?? 0;
                            double dRemainAmount = oe.GetRemainProject1(dtb.Rows[i]["bgm_proj_oper_seq"].ToString(), dtb.Rows[i]["bgm_source_seq"].ToString(), dtb.Rows[i]["bgm_exp_grp_seq"].ToString());

                            if (dBathAmount > dRemainAmount && mrInfo2.icm_dn_seq == null)
                            {
                                string errorStr = "ไม่สามารถอนุมัติได้ เนื่องจากจำนวนเงินเกินกว่าที่ได้รับอนุมัติ";
                                if (!directApprove) main.MessageAlert(Page, errorStr);
                                return errorStr;
                            }
                        }

                        dbManager.CreateParameters(5);

                        dbManager.AddParameters(0, "@money_req_seq", mrInfo.money_req_seq);
                        dbManager.AddParameters(1, "@record_status", mrInfo.record_status);
                        dbManager.AddParameters(2, "@updated_by", mrInfo.updated_by);
                        dbManager.AddParameters(3, "@updated_when", mrInfo.updated_when);
                        dbManager.AddParameters(4, "@borrow_no", mrInfo.borrow_no);

                        strSQL = "UPDATE fim_money_requests"
                            + " SET record_status = @record_status"
                            + ", borrow_no = @borrow_no"
                            + ", updated_by = @updated_by"
                            + ", updated_when = @updated_when"
                            + " WHERE money_req_seq = @money_req_seq";

                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                        dbManager.CreateParameters(3);

                        dbManager.AddParameters(0, "@delete_status", SystemInfo._DeleteRecordStatus);
                        dbManager.AddParameters(1, "@seq", Convert.ToInt32(strMoneyReqSeq));

                        int nPrevRptType = 0;
                        strSQL = "select rpt.bgm_proj_oper_rpt_seq, rpt.bgm_proj_oper_exp_seq, rpt.icm_ppr_item_seq"
                            + ", rpt.icm_pr_item_seq, rpt.icm_dn_item_seq, rpt.money_req_dtls_seq, rpt.return_dtls_seq"
                            + ", rpt.petition_dtls_seq, rpt.pay_seq, rpt.used_amount, rpt.rpt_type, rpt.receive_seq"
                            + ", rpt.cal_amount, dni.NetAmount"
                            + " from fim_money_requests mr"
                            + " left join IcmDeliveryNoteItem dni on mr.icm_dn_seq = dni.DnId"
                            + " left join IcmPurchaseOrderInstallmentItem poii on dni.PoInstallItemId = poii.PoInstallItemId"
                            + " left join IcmBidderQuotation quo on poii.BidderQuoId = quo.BidderQuoId"
                            + " left join bgm_project_operation_report rpt on quo.PrItemId = rpt.icm_pr_item_seq"

                            + " where mr.money_req_seq = @seq"
                            + " and rpt.record_status not like @delete_status";

                        dbManager.AddParameters(2, "@rpt_type", nPrevRptType);

                        var drc = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows;
                        if (drc.Count > 0)
                        {
                            for (int i = 0; i < drc.Count; i++)
                            {
                                BGM_ProjectOperationReport.M_BGM_ProjectOperationReport item = new BGM_ProjectOperationReport.M_BGM_ProjectOperationReport();
                                item.bgm_proj_oper_rpt_seq = Convert.ToInt32(drc[i]["bgm_proj_oper_rpt_seq"]);
                                item.bgm_proj_oper_exp_seq = main.ConvertNullInt(drc[i]["bgm_proj_oper_exp_seq"]);
                                //info.bgm_trans_from_seq = cn.ConvertNullInt(drc[i]["bgm_trans_from_seq"]);
                                //info.bgm_trans_to_seq = cn.ConvertNullInt(drc[i]["bgm_trans_to_seq"]);
                                item.icm_ppr_item_seq = main.ConvertNullInt(drc[i]["icm_ppr_item_seq"]);
                                item.icm_pr_item_seq = main.ConvertNullInt(drc[i]["icm_pr_item_seq"]);
                                item.icm_dn_item_seq = main.ConvertNullInt(drc[i]["icm_dn_item_seq"]);
                                item.money_req_dtls_seq = main.ConvertNullInt(drc[i]["money_req_dtls_seq"]);
                                item.return_dtls_seq = main.ConvertNullInt(drc[i]["return_dtls_seq"]);
                                item.petition_dtls_seq = main.ConvertNullInt(drc[i]["petition_dtls_seq"]);
                                item.pay_seq = main.ConvertNullInt(drc[i]["pay_seq"]);
                                item.used_amount = main.ConvertNullDouble(drc[i]["used_amount"]);
                                item.cal_amount = Math.Round(main.ConvertNullDouble(drc[i]["cal_amount"]) ?? 0, 2) + Math.Round(main.ConvertNullDouble(drc[i]["NetAmount"]) ?? 0, 2);
                                item.rpt_type = main.ConvertNullInt(drc[i]["rpt_type"]);
                                //item.receive_seq = main.ConvertNullInt(drc[0]["receive_seq"]);

                                dbManager.CreateParameters(13);

                                dbManager.AddParameters(0, "@bgm_proj_oper_rpt_seq", item.bgm_proj_oper_rpt_seq);
                                dbManager.AddParameters(1, "@descr", item.descr);
                                dbManager.AddParameters(2, "@bgm_proj_oper_exp_seq", item.bgm_proj_oper_exp_seq);
                                dbManager.AddParameters(3, "@bgm_trans_from_seq", "");
                                dbManager.AddParameters(4, "@bgm_trans_to_seq", "");
                                dbManager.AddParameters(5, "@money_req_dtls_seq", item.money_req_dtls_seq);
                                dbManager.AddParameters(6, "@return_dtls_seq", item.return_dtls_seq);
                                dbManager.AddParameters(7, "@petition_dtls_seq", item.petition_dtls_seq);
                                dbManager.AddParameters(8, "@pay_seq", item.pay_seq);

                                dbManager.AddParameters(9, "@used_amount", item.used_amount);
                                dbManager.AddParameters(10, "@cal_amount", item.cal_amount);

                                dbManager.AddParameters(11, "@updated_by", item.updated_by);
                                dbManager.AddParameters(12, "@updated_when", item.updated_when);

                                strSQL = "UPDATE bgm_project_operation_report"
                                    + " set descr = @descr"
                                    + ", bgm_proj_oper_exp_seq = @bgm_proj_oper_exp_seq"
                                    //+ ", bgm_trans_from_seq = @bgm_trans_from_seq"
                                    //+ ", bgm_trans_to_seq = @bgm_trans_to_seq"
                                    + ", money_req_dtls_seq = @money_req_dtls_seq"
                                    + ", return_dtls_seq = @return_dtls_seq"
                                    + ", petition_dtls_seq = @petition_dtls_seq"
                                    + ", pay_seq = @pay_seq"
                                    + ", used_amount = @used_amount"
                                    + ", cal_amount = @cal_amount"

                                    + ", updated_by = @updated_by"
                                    + ", updated_when = @updated_when"
                                    + " WHERE bgm_proj_oper_rpt_seq = @bgm_proj_oper_rpt_seq";

                                dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                            }
                        }

                        dbManager.CreateParameters(2);

                        dbManager.AddParameters(0, "@delete_status", SystemInfo._DeleteRecordStatus);
                        dbManager.AddParameters(1, "@money_req_seq", strMoneyReqSeq);

                        strSQL = "SELECT mrd.money_req_dtls_seq, mrd.money_req_seq, mrd.money_req_dtls_name"
                            + ", mrd.bgm_proj_oper_exp_seq, mrd.percent_vat, mrd.percent_tax"
                            + ", mrd.amount, mrd.amount_vat, mrd.amount_tax, mrd.amount_fund, mrd.bath_amount_tax"
                            + ", coalesce(mrd.amount, 0) - coalesce(mrd.amount_vat, 0) as exclude_vat"

                            + ", recexp.bgm_exp_seq, exp.bgm_exp_name, exp.bgm_exp_grp_seq"
                            + ", exp1.bgm_exp_seq as bgm_exp_seq1, exp1.bgm_exp_name as bgm_exp_name1"
                            + ", exp2.bgm_exp_seq as bgm_exp_seq2, exp2.bgm_exp_name as bgm_exp_name2"

                            + ", mrd.record_status, mrd.remarks"
                            + ", mrd.created_by, mrd.created_when, mrd.updated_by, mrd.updated_when"
                            + " FROM fim_money_request_dtls mrd"
                            + " LEFT JOIN bgm_project_operation_expense pjexp ON mrd.bgm_proj_oper_exp_seq = pjexp.bgm_proj_oper_exp_seq"
                            + " LEFT JOIN bgm_project_expense recexp ON pjexp.bgm_proj_exp_seq = recexp.bgm_proj_exp_seq"
                            + " LEFT JOIN bgm_mas_expense exp ON recexp.bgm_exp_seq = exp.bgm_exp_seq"
                            + " LEFT JOIN bgm_mas_expense exp1 ON exp.upper_bgm_exp_seq = exp1.bgm_exp_seq"
                            + " LEFT JOIN bgm_mas_expense exp2 ON exp1.upper_bgm_exp_seq = exp2.bgm_exp_seq"
                            + " WHERE mrd.record_status not like @delete_status"
                            + " and mrd.money_req_seq = @money_req_seq"
                            + " ORDER BY mrd.money_req_dtls_seq";

                        drc = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows;
                        if (drc.Count > 0)
                        {
                            for (int i = 0; i < drc.Count; i++)
                            {
                                FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls item = new FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls();
                                item.money_req_dtls_seq = Convert.ToInt32(drc[i]["money_req_dtls_seq"]);
                                item.money_req_seq = main.ConvertNullInt(drc[i]["money_req_seq"]);
                                item.money_req_dtls_name = drc[i]["money_req_dtls_name"].ToString();
                                item.bgm_proj_oper_exp_seq = main.ConvertNullInt(drc[i]["bgm_proj_oper_exp_seq"]);
                                item.percent_vat = main.ConvertNullDouble(drc[i]["percent_vat"]);
                                item.percent_tax = main.ConvertNullDouble(drc[i]["percent_tax"]);
                                item.amount = main.ConvertNullDouble(drc[i]["amount"]);
                                item.amount_vat = main.ConvertNullDouble(drc[i]["amount_vat"]);
                                item.amount_tax = main.ConvertNullDouble(drc[i]["amount_tax"]);
                                item.amount_fund = main.ConvertNullDouble(drc[i]["amount_fund"]);
                                item.remarks = drc[i]["remarks"].ToString();
                                item.exclude_vat = main.ConvertNullDouble(drc[i]["exclude_vat"]);
                                item.bath_amount_tax = main.ConvertNullDouble(drc[i]["bath_amount_tax"]);
                                item.bgm_exp_name = drc[i]["bgm_exp_name"].ToString();

                                item.record_status = drc[i]["record_status"].ToString();
                                item.created_by = main.ConvertNullInt(drc[i]["created_by"]);
                                item.created_when = main.ConvertNullDateTime(drc[i]["created_when"]);
                                item.updated_by = main.ConvertNullInt(drc[i]["updated_by"]);
                                item.updated_when = main.ConvertNullDateTime(drc[i]["updated_when"]);
                                BGM_ProjectOperationReport.M_BGM_ProjectOperationReport reportInfo = new BGM_ProjectOperationReport.M_BGM_ProjectOperationReport();
                                reportInfo.bgm_proj_oper_exp_seq = item.bgm_proj_oper_exp_seq;
                                reportInfo.descr = lblMoneyReqName.Text;
                                reportInfo.money_req_dtls_seq = item.money_req_dtls_seq;
                                reportInfo.used_amount = item.amount;
                                reportInfo.cal_amount = -item.amount;
                                reportInfo.rpt_type = 6;//กันเงิน
                                reportInfo.created_by = nEmpSeqLogin;
                                reportInfo.created_when = DateTime.Now;

                                dbManager.CreateParameters(15);

                                dbManager.AddParameters(0, "@bgm_proj_oper_rpt_seq", reportInfo.bgm_proj_oper_rpt_seq);
                                dbManager.AddParameters(1, "@descr", reportInfo.descr);
                                dbManager.AddParameters(2, "@bgm_proj_oper_exp_seq", reportInfo.bgm_proj_oper_exp_seq);
                                dbManager.AddParameters(3, "@bgm_trans_from_seq", "");
                                dbManager.AddParameters(4, "@bgm_trans_to_seq", "");
                                dbManager.AddParameters(5, "@money_req_dtls_seq", reportInfo.money_req_dtls_seq);
                                dbManager.AddParameters(6, "@return_dtls_seq", reportInfo.return_dtls_seq);
                                dbManager.AddParameters(7, "@petition_dtls_seq", reportInfo.petition_dtls_seq);
                                dbManager.AddParameters(8, "@pay_seq", reportInfo.pay_seq);

                                dbManager.AddParameters(9, "@used_amount", reportInfo.used_amount);
                                dbManager.AddParameters(10, "@cal_amount", reportInfo.cal_amount);
                                dbManager.AddParameters(11, "@rpt_type", reportInfo.rpt_type);

                                dbManager.AddParameters(12, "@record_status", SystemInfo._ActiveRecordStatus);
                                dbManager.AddParameters(13, "@created_by", reportInfo.created_by);
                                dbManager.AddParameters(14, "@created_when", reportInfo.created_when);

                                strSQL = "select count(*) as row_count"
                                    + " from bgm_project_operation_report"
                                    + " where money_req_dtls_seq = @money_req_dtls_seq"
                                    + " and record_status <> 'D'";
                                var exists = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                                if (exists.Rows.Count > 0 && (main.ConvertNullInt(exists.Rows[0][0]) ?? 0) > 0)
                                {
                                    dbManager.RollBackTransaction();
                                    main.MessageAlert(Page, "มีการทำรายการซ้ำ");
                                    return "";
                                }

                                strSQL = "INSERT INTO bgm_project_operation_report"
                                    + "(descr, bgm_proj_oper_exp_seq"//, bgm_trans_from_seq, bgm_trans_to_seq"
                                        + ", money_req_dtls_seq, return_dtls_seq, petition_dtls_seq, pay_seq"
                                        + ", used_amount, cal_amount, rpt_type"
                                        + ", record_status, created_by, created_when)"
                                    + " VALUES (@descr, @bgm_proj_oper_exp_seq"//, @bgm_trans_from_seq, @bgm_trans_to_seq"
                                        + ", @money_req_dtls_seq, @return_dtls_seq, @petition_dtls_seq, @pay_seq"
                                        + ", @used_amount, @cal_amount, @rpt_type"
                                        + ", @record_status, @created_by, @created_when)";

                                dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                            }
                        }

                        replyInfo.reply_date = DateTime.Today;
                        replyInfo.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                        replyInfo.reply_type = "1";
                        replyInfo.reply_text = "อนุมัติ : " + lblMoneyReqName.Text;
                        replyInfo.from_emp_seq = nFromEmpSeq;
                        replyInfo.from_pos_seq = nFromPosSeq;
                        replyInfo.to_emp_seq = nToEmpSeq;
                        replyInfo.to_pos_seq = nToPosSeq;
                        replyInfo.wod_emp_seq = nWodEmpSeq;
                        replyInfo.from_send_seq = Convert.ToInt32(lblSendSeq.Text);
                        replyInfo.message_status = "0";
                        replyInfo.created_by = nEmpSeqLogin;
                        replyInfo.created_when = DateTime.Now;
                        replyInfo.remarks = txtRemark.Text;
                        //reply.Insert(replyInfo);

                        dbManager.CreateParameters(16);

                        dbManager.AddParameters(0, "@reply_seq", replyInfo.reply_seq);
                        dbManager.AddParameters(1, "@reply_date", replyInfo.reply_date == null ? DBNull.Value : (object)replyInfo.reply_date);
                        dbManager.AddParameters(2, "@ref_no", replyInfo.ref_no == null ? DBNull.Value : (object)replyInfo.ref_no);
                        dbManager.AddParameters(3, "@reply_text", replyInfo.reply_text == null ? DBNull.Value : (object)replyInfo.reply_text);
                        dbManager.AddParameters(4, "@reply_type", replyInfo.reply_type == null ? DBNull.Value : (object)replyInfo.reply_type);
                        dbManager.AddParameters(5, "@from_emp_seq", replyInfo.from_emp_seq == null ? DBNull.Value : (object)replyInfo.from_emp_seq);
                        dbManager.AddParameters(6, "@to_emp_seq", replyInfo.to_emp_seq == null ? DBNull.Value : (object)replyInfo.to_emp_seq);
                        dbManager.AddParameters(7, "@from_send_seq", replyInfo.from_send_seq == null ? DBNull.Value : (object)replyInfo.from_send_seq);
                        dbManager.AddParameters(8, "@remarks", replyInfo.remarks == null ? DBNull.Value : (object)replyInfo.remarks);
                        dbManager.AddParameters(9, "@message_status", replyInfo.message_status == null ? DBNull.Value : (object)replyInfo.message_status);

                        dbManager.AddParameters(10, "@record_status", SystemInfo._ActiveRecordStatus);
                        dbManager.AddParameters(11, "@created_by", replyInfo.created_by);
                        dbManager.AddParameters(12, "@created_when", replyInfo.created_when);

                        dbManager.AddParameters(13, "@from_pos_seq", replyInfo.from_pos_seq);
                        dbManager.AddParameters(14, "@to_pos_seq", replyInfo.to_pos_seq);
                        dbManager.AddParameters(15, "@wod_emp_seq", replyInfo.wod_emp_seq);

                        strSQL = "INSERT INTO message_reply"
                            + "(reply_date, ref_no, reply_text, reply_type"
                            + ", from_emp_seq, to_emp_seq, from_send_seq, remarks, message_status"
                            + ", from_pos_seq, to_pos_seq, wod_emp_seq"
                            + ", record_status, created_by, created_when)"
                            + " VALUES(@reply_date"
                                + ", @ref_no"
                                + ", @reply_text"
                                + ", @reply_type"
                                + ", @from_emp_seq"
                                + ", @to_emp_seq"
                                + ", @from_send_seq"
                                + ", @remarks"
                                + ", @message_status"
                                + ", @from_pos_seq"
                                + ", @to_pos_seq"
                                + ", @wod_emp_seq"

                                + ", @record_status"
                                + ", @created_by"
                                + ", @created_when);"
                            + " SELECT scope_identity();";
                        var strSeq = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0].ToString();

                        info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                        info.message_status = "2";
                        info.wod_emp_seq = nWodEmpSeq;
                        info.updated_by = nEmpSeqLogin;
                        info.updated_when = DateTime.Now;
                        //send.UpdateMessageStatus(info);

                        dbManager.CreateParameters(5);

                        dbManager.AddParameters(0, "@send_seq", info.send_seq);
                        dbManager.AddParameters(1, "@message_status", info.message_status);
                        dbManager.AddParameters(2, "@updated_by", info.updated_by);
                        dbManager.AddParameters(3, "@updated_when", info.updated_when);
                        dbManager.AddParameters(4, "@wod_emp_seq", info.wod_emp_seq);

                        strSQL = "UPDATE message_send"
                            + " SET message_status = @message_status"
                            + ", updated_by = @updated_by"
                            + ", updated_when = @updated_when"
                                 + ", wod_emp_seq = @wod_emp_seq"
                            + " WHERE send_seq = @send_seq";

                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                        // new requirement ==================================================================================
                        #region new requirement
                        if (mrInfo2.event_seq != 16 && mrInfo2.use_advance != "1")
                        {
                            string strTranCode = "";
                            string strTranCode2 = "";
                            int nBgmYear = mrInfo2.money_req_date.Value.Month >= 10 ? mrInfo2.money_req_date.Value.Year + 544 : mrInfo2.money_req_date.Value.Year + 543;

                            strSQL = "SELECT max(CONVERT(VARCHAR(50),tran_code)) as tran_code"
                                + " from acm_transection"
                                + " where record_status not like 'D'"
                                + " and bgm_source_seq = " + (mrInfo2.bgm_source_seq == 1 ? "1" : "2")
                                + " and bgm_year = " + nBgmYear
                                + " and tran_type = 'G'"
                                + " group by bgm_source_seq, bgm_year, tran_type";

                            dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                            if (dtb.Rows.Count > 0)
                            {
                                if (dtb.Rows[0]["tran_code"] != DBNull.Value && !string.IsNullOrEmpty(dtb.Rows[0]["tran_code"].ToString()))
                                {
                                    strTranCode = "G-" + (mrInfo2.bgm_source_seq == 1 ? "1" : "2") + "-" + nBgmYear + "-" + (Convert.ToInt32(dtb.Rows[0]["tran_code"].ToString().Split('-')[3]) + 1).ToString("00000");
                                    strTranCode2 = "G-" + (mrInfo2.bgm_source_seq == 1 ? "1" : "2") + "-" + nBgmYear + "-" + (Convert.ToInt32(dtb.Rows[0]["tran_code"].ToString().Split('-')[3]) + 2).ToString("00000");
                                }
                                else
                                {
                                    strTranCode = "G-" + (mrInfo2.bgm_source_seq == 1 ? "1" : "2") + "-" + nBgmYear + "-00001";
                                    strTranCode2 = "G-" + (mrInfo2.bgm_source_seq == 1 ? "1" : "2") + "-" + nBgmYear + "-00002";
                                }
                            }

                            strSQL = "SELECT max(coalesce(tran_grp_seq, 0)) as tran_grp_seq"
                                + " from acm_transection"
                                + " where record_status not like 'D'";
                            int nTranGrpSeq = main.ConvertNullInt(dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0]) ?? -1;

                            dbManager.CreateParameters(14);

                            dbManager.AddParameters(0, "@tran_type", "G");
                            dbManager.AddParameters(1, "@fiscal_period", GetFiscalPeriod(mrInfo2.money_req_date.Value));
                            dbManager.AddParameters(2, "@tran_grp_seq", nTranGrpSeq);
                            dbManager.AddParameters(3, "@tran_code", strTranCode);
                            dbManager.AddParameters(4, "@tran_date", mrInfo2.money_req_date);
                            dbManager.AddParameters(5, "@bgm_year", nBgmYear);
                            dbManager.AddParameters(6, "@work_area_seq", 0);
                            dbManager.AddParameters(7, "@bgm_source_seq", mrInfo2.bgm_source_seq);
                            dbManager.AddParameters(8, "@ref_no", mrInfo2.ref_no);
                            dbManager.AddParameters(9, "@tran_name", mrInfo2.money_req_name);
                            dbManager.AddParameters(10, "@remarks", mrInfo2.remarks);
                            dbManager.AddParameters(11, "@record_status", "W");
                            dbManager.AddParameters(12, "@created_by", nEmpSeqLogin);
                            dbManager.AddParameters(13, "@created_when", DateTime.Now);

                            strSQL = @"
insert into acm_transection
(tran_type, fiscal_period, tran_grp_seq, tran_code, tran_date, bgm_year, work_area_seq, bgm_source_seq, ref_no, tran_name, remarks, record_status, created_by, created_when)
values
(@tran_type, @fiscal_period, @tran_grp_seq, @tran_code, @tran_date, @bgm_year, @work_area_seq, @bgm_source_seq, @ref_no, @tran_name, @remarks, @record_status, @created_by, @created_when);
select scope_identity();
";

                            string strTranSeq = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0].ToString();
                            strSQL = @"
update fim_money_requests
set tran_grp_seq = " + strTranSeq
+ @" where money_req_seq = " + strMoneyReqSeq
;
                            dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                            switch (mrInfo2.event_seq)
                            {
                                #region 11
                                case 11:
                                    dbManager.CreateParameters(1);
                                    dbManager.AddParameters(0, "@ref_seq", mrInfo2.money_req_seq);
                                    strSQL = @"
SELECT acc1.account_seq as account_seq1
, acc1.account_code as account_code1
, acc1.account_name as account_name1
, acc2.account_seq as account_seq2
, acc2.account_code as account_code2
, acc2.account_name as account_name2
, coalesce(mrd.amount, 0) as amount
, coalesce(mrd.amount_vat, 0) as amount_vat
FROM fim_money_requests mr
LEFT JOIN (select mrd.money_req_seq
	, sum(coalesce(mrd.amount, 0)) as amount
	, sum(coalesce(mrd.amount_vat, 0)) as amount_vat
	from fim_money_request_dtls mrd
	where mrd.record_status not like 'D'
	group by mrd.money_req_seq
) mrd ON mr.money_req_seq = mrd.money_req_seq
cross join acm_mas_base_account ba
LEFT JOIN acm_mas_account acc1 ON ba.direct_pay_account_seq = acc1.account_seq
LEFT JOIN acm_mas_account acc2 ON ba.dn_cr_account_seq = acc2.account_seq
WHERE mr.money_req_seq = @ref_seq
";
                                    dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                                    strSQL = @"
Insert into acm_transection_dtls
(tran_seq, account_seq, dr_or_cr, amount, record_status, created_by, created_when)
values
(@tran_seq, @account_seq, @dr_or_cr, @amount, @record_status, @created_by, @created_when);
";

                                    foreach (DataRow dr in dtb.Rows)
                                    {
                                        dbManager.CreateParameters(7);
                                        dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                        dbManager.AddParameters(1, "@account_seq", dr["account_seq1"].ToString());
                                        dbManager.AddParameters(2, "@dr_or_cr", "Dr");
                                        dbManager.AddParameters(3, "@amount", (main.ConvertNullDouble(dr["amount"]) ?? 0));
                                        dbManager.AddParameters(4, "@record_status", "W");
                                        dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                        dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                                        dbManager.CreateParameters(7);
                                        dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                        dbManager.AddParameters(1, "@account_seq", dr["account_seq2"].ToString());
                                        dbManager.AddParameters(2, "@dr_or_cr", "Cr");
                                        dbManager.AddParameters(3, "@amount", main.ConvertNullDouble(dr["amount"]) ?? 0);
                                        dbManager.AddParameters(4, "@record_status", "W");
                                        dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                        dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                                    }

                                    dbManager.CreateParameters(1);
                                    dbManager.AddParameters(0, "@icm_dn_seq", mrInfo2.icm_dn_seq);
                                    strSQL = "SELECT dn.Code as ref_no"
                                        + ", dn.ReceiveDate as tran_date"
                                        + ", dn.Name as tran_name, dn.Descr"
                                        + ", dn.TranGrpId"
                                        + " FROM IcmDeliveryNote dn"
                                        + " where dn.DnId = @icm_dn_seq";
                                    DataTable dtbDN = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                                    if (!string.IsNullOrEmpty(dtbDN.Rows[0]["tran_date"].ToString()))
                                    {

                                        dbManager.CreateParameters(14);

                                        dbManager.AddParameters(0, "@tran_type", "G");
                                        dbManager.AddParameters(1, "@fiscal_period", GetFiscalPeriod(main.ConvertNullDateTime(dtbDN.Rows[0]["tran_date"]) ?? DateTime.Today));
                                        dbManager.AddParameters(2, "@tran_grp_seq", nTranGrpSeq);
                                        dbManager.AddParameters(3, "@tran_code", strTranCode2);
                                        dbManager.AddParameters(4, "@tran_date", main.ConvertNullDateTime(dtbDN.Rows[0]["tran_date"]));
                                        dbManager.AddParameters(5, "@bgm_year", nBgmYear);
                                        dbManager.AddParameters(6, "@work_area_seq", 0);
                                        dbManager.AddParameters(7, "@bgm_source_seq", mrInfo2.bgm_source_seq);
                                        dbManager.AddParameters(8, "@ref_no", dtbDN.Rows[0]["ref_no"].ToString());
                                        dbManager.AddParameters(9, "@tran_name", dtbDN.Rows[0]["tran_name"].ToString());
                                        dbManager.AddParameters(10, "@remarks", dtbDN.Rows[0]["Descr"].ToString());
                                        dbManager.AddParameters(11, "@record_status", "W");
                                        dbManager.AddParameters(12, "@created_by", nEmpSeqLogin);
                                        dbManager.AddParameters(13, "@created_when", DateTime.Now);
                                        strSQL = @"
insert into acm_transection
(tran_type, fiscal_period, tran_grp_seq, tran_code, tran_date, bgm_year, work_area_seq, bgm_source_seq, ref_no, tran_name, remarks, record_status, created_by, created_when)
values
(@tran_type, @fiscal_period, @tran_grp_seq, @tran_code, @tran_date, @bgm_year, @work_area_seq, @bgm_source_seq, @ref_no, @tran_name, @remarks, @record_status, @created_by, @created_when);
select scope_identity();
";
                                        strTranSeq = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0].ToString();

                                        strSQL = @"
update IcmDeliveryNote
set TranGrpId = " + strTranSeq
    + @" where DnId = " + mrInfo2.icm_dn_seq
    ;
                                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                                        // quotation อะไรบ้างใน dn นี้
                                        dbManager.CreateParameters(1);
                                        dbManager.AddParameters(0, "@icm_dn_seq", mrInfo2.icm_dn_seq);
                                        strSQL = @"
select poii.BidderQuoId, coalesce(dni.HaveItem, 1) as HaveItem
from IcmDeliveryNoteItem dni
left join IcmPurchaseOrderInstallmentItem poii on dni.PoInstallItemId = poii.PoInstallItemId
where dni.DnId = @icm_dn_seq
";
                                        DataTable dtbQuotation = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                                        for (int i = 0; i < dtbQuotation.Rows.Count; i++)
                                        {
                                            // มีงานระหว่างทำหรือไม่
                                            dbManager.CreateParameters(2);
                                            dbManager.AddParameters(0, "@BidderQuoId", dtbQuotation.Rows[i]["BidderQuoId"].ToString());
                                            dbManager.AddParameters(1, "@DnId", mrInfo2.icm_dn_seq);
                                            strSQL = @"
select count(*) as row_count
from IcmPurchaseOrderInstallmentItem poii
left join IcmDeliveryNoteItem dni on poii.PoInstallItemId = dni.PoInstallItemId
where poii.BidderQuoId = @BidderQuoId
and HaveItem = 0
";
                                            int nRowCount = Convert.ToInt32(dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0]);

                                            // ถ้าไม่เป็นงานระหว่างทำ จะต้องเช็คว่ามีงานระหว่างทำรึเปล่า
                                            if (dtbQuotation.Rows[i]["HaveItem"].ToString() == "1" && nRowCount > 0)
                                            {
                                                // ถ้ามีงานระหว่างทำ ให้ลงงานระหว่างทำก่อน
                                                strSQL = @"
select wait_account_seq as account1, suspense_input_tax_account_seq as account3, direct_pay_account_seq as account4, income_from_penalty_account_seq as account5
, sum(coalesce(dni.NetAmount, 0)) as NetAmount, sum(coalesce(dni.VatAmount, 0)) as VatAmount, coalesce(pen.amount, 0) as PenAmount
from IcmDeliveryNoteItem dni
left join IcmPurchaseOrderInstallmentItem poii on dni.PoInstallItemId = poii.PoInstallItemId
left join (select DnId, sum(coalesce(PenaltyFinalAmount, 0)) as amount
    from IcmDeliveryNotePenalty
    group by DnId
    ) pen on dni.DnId = pen.DnId
cross join acm_mas_base_account
where poii.BidderQuoId = @BidderQuoId
and dni.DnId = @DnId
group by wait_account_seq, suspense_input_tax_account_seq, direct_pay_account_seq, income_from_penalty_account_seq, pen.amount
";
                                                DataTable dtbDni = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                                                strSQL = @"
Insert into acm_transection_dtls
(tran_seq, account_seq, dr_or_cr, amount, record_status, created_by, created_when)
values
(@tran_seq, @account_seq, @dr_or_cr, @amount, @record_status, @created_by, @created_when);
";
                                                if (dtbDni.Rows.Count > 0)
                                                {
                                                    dbManager.CreateParameters(7);
                                                    dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                                    dbManager.AddParameters(1, "@account_seq", dtbDni.Rows[0]["account1"].ToString());
                                                    dbManager.AddParameters(2, "@dr_or_cr", "Dr");
                                                    dbManager.AddParameters(3, "@amount", (main.ConvertNullDouble(dtbDni.Rows[0]["NetAmount"]) ?? 0) - (main.ConvertNullDouble(dtbDni.Rows[0]["VatAmount"]) ?? 0));
                                                    dbManager.AddParameters(4, "@record_status", "W");
                                                    dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                                    dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                                    dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                                                    if ((main.ConvertNullDouble(dtbDni.Rows[0]["VatAmount"]) ?? 0) != 0)
                                                    {
                                                        dbManager.CreateParameters(7);
                                                        dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                                        dbManager.AddParameters(1, "@account_seq", dtbDni.Rows[0]["account3"].ToString());
                                                        dbManager.AddParameters(2, "@dr_or_cr", "Dr");
                                                        dbManager.AddParameters(3, "@amount", (main.ConvertNullDouble(dtbDni.Rows[0]["VatAmount"]) ?? 0));
                                                        dbManager.AddParameters(4, "@record_status", "W");
                                                        dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                                        dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                                                    }

                                                    dbManager.CreateParameters(7);
                                                    dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                                    dbManager.AddParameters(1, "@account_seq", dtbDni.Rows[0]["account4"].ToString());
                                                    dbManager.AddParameters(2, "@dr_or_cr", "Cr");
                                                    dbManager.AddParameters(3, "@amount", (main.ConvertNullDouble(dtbDni.Rows[0]["NetAmount"]) ?? 0) - main.ConvertNullDouble(dtbDni.Rows[0]["PenAmount"]) ?? 0);
                                                    dbManager.AddParameters(4, "@record_status", "W");
                                                    dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                                    dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                                    dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                                                    if ((main.ConvertNullDouble(dtbDni.Rows[0]["PenAmount"]) ?? 0) != 0)
                                                    {
                                                        dbManager.CreateParameters(7);
                                                        dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                                        dbManager.AddParameters(1, "@account_seq", dtbDni.Rows[0]["account5"].ToString());
                                                        dbManager.AddParameters(2, "@dr_or_cr", "Cr");
                                                        dbManager.AddParameters(3, "@amount", main.ConvertNullDouble(dtbDni.Rows[0]["PenAmount"]) ?? 0);
                                                        dbManager.AddParameters(4, "@record_status", "W");
                                                        dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                                        dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                                                    }
                                                }

                                                dbManager.CreateParameters(1);
                                                dbManager.AddParameters(0, "@BidderQuoId", dtbQuotation.Rows[i]["BidderQuoId"].ToString());

                                                strSQL = @"
select sum(coalesce(dni.NetAmount, 0)) as Amount
, sum(coalesce(dni.VatAmount, 0)) as VatAmount
, ba.wait_account_seq
, case when ri.ResItemId is not null and rg.ResTypeId <> 1
	then rg.AssetAccountId
	else ex.account_seq
	end as account_seq1
from IcmPurchaseOrderInstallmentItem poii
left join IcmDeliveryNoteItem dni on poii.PoInstallItemId = dni.PoInstallItemId
left join IcmBidderQuotation q on poii.BidderQuoId = q.BidderQuoId
left join IcmPurchaseRequestItem ri on q.PrItemId = ri.PrItemId
left join bgm_mas_expense ex on ri.BgExpId = ex.bgm_exp_seq
left join IcmMasResourceItem mi on ri.ResItemId = mi.ResItemId
left join IcmMasResourceSubGroup sg on mi.ResSubGrpId = sg.ResSubGrpId
left join IcmMasResourceGroup rg on sg.ResGrpId = rg.ResGrpId
LEFT JOIN acm_mas_account acc1 ON rg.AssetAccountId = acc1.account_seq
LEFT JOIN acm_mas_account acc2 ON ex.account_seq = acc2.account_seq
cross join acm_mas_base_account ba
where poii.BidderQuoId = @BidderQuoId
group by ba.wait_account_seq, ri.ResItemId, rg.ResTypeId, rg.AssetAccountId, ex.account_seq
";
                                                DataTable dtbDni2 = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                                                double dAmount = main.ConvertNullDouble(dtbDni2.Rows[0][0]) ?? 0;
                                                double dVatAmount = main.ConvertNullDouble(dtbDni2.Rows[0][1]) ?? 0;
                                                string strWaitAccountSeq = dtbDni2.Rows[0][2].ToString();
                                                string strAssetAccountSeq = dtbDni2.Rows[0][3].ToString();

                                                strSQL = @"
Insert into acm_transection_dtls
(tran_seq, account_seq, dr_or_cr, amount, record_status, created_by, created_when)
values
(@tran_seq, @account_seq, @dr_or_cr, @amount, @record_status, @created_by, @created_when);
";
                                                if (dtbDni2.Rows.Count > 0)
                                                {
                                                    dbManager.CreateParameters(7);
                                                    dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                                    dbManager.AddParameters(1, "@account_seq", strAssetAccountSeq);
                                                    dbManager.AddParameters(2, "@dr_or_cr", "Dr");
                                                    dbManager.AddParameters(3, "@amount", dAmount - dVatAmount);
                                                    dbManager.AddParameters(4, "@record_status", "W");
                                                    dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                                    dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                                    dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                                                    dbManager.CreateParameters(7);
                                                    dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                                    dbManager.AddParameters(1, "@account_seq", strWaitAccountSeq);
                                                    dbManager.AddParameters(2, "@dr_or_cr", "Cr");
                                                    dbManager.AddParameters(3, "@amount", dAmount - dVatAmount);
                                                    dbManager.AddParameters(4, "@record_status", "W");
                                                    dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                                    dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                                    dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                                                }
                                            }
                                            else
                                            {
                                                dbManager.CreateParameters(2);
                                                dbManager.AddParameters(0, "@BidderQuoId", dtbQuotation.Rows[i]["BidderQuoId"].ToString());
                                                dbManager.AddParameters(1, "@DnId", mrInfo2.icm_dn_seq);

                                                strSQL = @"
select account_seq1, account_code1, account_name1
, account_seq3
, account_code3
, account_name3
, account_seq4
, account_code4
, account_name4
, account_seq5
, account_code5
, account_name5
, account_seq6
, account_code6
, account_name6
, HaveItem
, sum(coalesce(amount, 0)) as amount
, sum(coalesce(amount_vat, 0)) as amount_vat
, coalesce(amount_penalty, 0) as amount_penalty
from (SELECT case when ri.ResItemId is not null and rg.ResTypeId <> 1
	then rg.AssetAccountId
	else ex.account_seq
	end as account_seq1
, case when ri.ResItemId is not null and rg.ResTypeId <> 1
	then acc1.account_code
	else acc2.account_code
	end as account_code1
, case when ri.ResItemId is not null and rg.ResTypeId <> 1
	then acc1.account_name
	else acc2.account_name
	end as account_name1
, acc3.account_seq as account_seq3
, acc3.account_code as account_code3
, acc3.account_name as account_name3
, acc4.account_seq as account_seq4
, acc4.account_code as account_code4
, acc4.account_name as account_name4
, acc5.account_seq as account_seq5
, acc5.account_code as account_code5
, acc5.account_name as account_name5
, acc6.account_seq as account_seq6
, acc6.account_code as account_code6
, acc6.account_name as account_name6
, coalesce(ni.NetAmount, 0) as amount
, COALESCE(ni.VatAmount, 0) as amount_vat
, coalesce(pen.amount, 0) as amount_penalty
, ni.HaveItem

FROM IcmDeliveryNoteItem ni
left join IcmPurchaseOrderInstallmentItem ii on ni.PoInstallItemId = ii.PoInstallItemId
left join IcmBidderQuotation q on ii.BidderQuoId = q.BidderQuoId
left join IcmPurchaseRequestItem ri on q.PrItemId = ri.PrItemId
left join bgm_mas_expense ex on ri.BgExpId = ex.bgm_exp_seq
left join IcmMasResourceItem mi on ri.ResItemId = mi.ResItemId
left join IcmMasResourceSubGroup sg on mi.ResSubGrpId = sg.ResSubGrpId
left join IcmMasResourceGroup rg on sg.ResGrpId = rg.ResGrpId
LEFT JOIN acm_mas_account acc1 ON rg.AssetAccountId = acc1.account_seq
LEFT JOIN acm_mas_account acc2 ON ex.account_seq = acc2.account_seq
cross join acm_mas_base_account ba
LEFT JOIN acm_mas_account acc3 ON ba.suspense_input_tax_account_seq = acc3.account_seq
LEFT JOIN acm_mas_account acc4 ON ba.direct_pay_account_seq = acc4.account_seq
LEFT JOIN acm_mas_account acc5 ON ba.wait_account_seq = acc5.account_seq
LEFT JOIN acm_mas_account acc6 ON ba.income_from_penalty_account_seq = acc6.account_seq
left join (select DnId, sum(coalesce(PenaltyFinalAmount, 0)) as amount
    from IcmDeliveryNotePenalty
    group by DnId
    ) pen on ni.DnId = pen.DnId
WHERE ni.DnId = @DnId
and ii.BidderQuoId = @BidderQuoId
) t
group by account_seq1, account_code1, account_name1
, account_seq3
, account_code3
, account_name3
, account_seq4
, account_code4
, account_name4
, account_seq5
, account_code5
, account_name5
, account_seq6
, account_code6
, account_name6
, HaveItem, amount_penalty";
                                                DataTable dtbDNDtls = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                                                strSQL = @"
Insert into acm_transection_dtls
(tran_seq, account_seq, dr_or_cr, amount, record_status, created_by, created_when)
values
(@tran_seq, @account_seq, @dr_or_cr, @amount, @record_status, @created_by, @created_when);
";
                                                double dAmount = 0;
                                                foreach (DataRow dr in dtbDNDtls.Rows)
                                                {
                                                    dbManager.CreateParameters(7);
                                                    dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                                    dbManager.AddParameters(1, "@account_seq", dr["HaveItem"].ToString() == "False" ? dr["account_seq5"].ToString() : dr["account_seq1"].ToString());
                                                    dbManager.AddParameters(2, "@dr_or_cr", "Dr");
                                                    dbManager.AddParameters(3, "@amount", (main.ConvertNullDouble(dr["amount"]) ?? 0) - (main.ConvertNullDouble(dr["amount_vat"]) ?? 0));
                                                    dbManager.AddParameters(4, "@record_status", "W");
                                                    dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                                    dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                                    dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                                                    dAmount += main.ConvertNullDouble(dr["amount"]) ?? 0;

                                                    if ((main.ConvertNullDouble(dr["amount_vat"]) ?? 0) != 0)
                                                    {
                                                        dbManager.CreateParameters(7);
                                                        dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                                        dbManager.AddParameters(1, "@account_seq", dr["account_seq3"].ToString());
                                                        dbManager.AddParameters(2, "@dr_or_cr", "Dr");
                                                        dbManager.AddParameters(3, "@amount", (main.ConvertNullDouble(dr["amount_vat"]) ?? 0));
                                                        dbManager.AddParameters(4, "@record_status", "W");
                                                        dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                                        dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                                                    }
                                                }

                                                dbManager.CreateParameters(7);
                                                dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                                dbManager.AddParameters(1, "@account_seq", dtbDNDtls.Rows[0]["account_seq4"].ToString());
                                                dbManager.AddParameters(2, "@dr_or_cr", "Cr");
                                                dbManager.AddParameters(3, "@amount", dAmount - main.ConvertNullDouble(dtbDNDtls.Rows[0]["amount_penalty"]) ?? 0);
                                                dbManager.AddParameters(4, "@record_status", "W");
                                                dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                                dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                                dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                                                if ((main.ConvertNullDouble(dtbDNDtls.Rows[0]["amount_penalty"]) ?? 0) != 0)
                                                {
                                                    dbManager.CreateParameters(7);
                                                    dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                                    dbManager.AddParameters(1, "@account_seq", dtbDNDtls.Rows[0]["account_seq6"].ToString());
                                                    dbManager.AddParameters(2, "@dr_or_cr", "Cr");
                                                    dbManager.AddParameters(3, "@amount", main.ConvertNullDouble(dtbDNDtls.Rows[0]["amount_penalty"]) ?? 0);
                                                    dbManager.AddParameters(4, "@record_status", "W");
                                                    dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                                    dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                                    dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                                                }
                                            }
                                        }

                                        dbManager.CreateParameters(4);
                                        dbManager.AddParameters(0, "@DnId", mrInfo2.icm_dn_seq);
                                        dbManager.AddParameters(1, "@TranGrpId", strTranSeq);
                                        dbManager.AddParameters(2, "@UpdatedBy", nEmpSeqLogin);
                                        dbManager.AddParameters(3, "@UpdatedWhen", DateTime.Now);

                                        strSQL = "UPDATE IcmDeliveryNote"
                                            + " SET TranGrpId = @TranGrpId"
                                            + ", UpdatedBy = @UpdatedBy"
                                            + ", UpdatedWhen = @UpdatedWhen"
                                            + " WHERE DnId = @DnId";

                                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                                    }
                                    break;
                                #endregion
                                #region 12
                                case 12:
                                case 14:
                                case 15:
                                case 17:
                                case 18:
                                default:
                                    dbManager.CreateParameters(1);
                                    dbManager.AddParameters(0, "@ref_seq", mrInfo2.money_req_seq);
                                    strSQL = @"
SELECT acc1.account_seq as account_seq1
, acc1.account_code as account_code1
, acc1.account_name as account_name1
, acc2.account_seq as account_seq2
, acc2.account_code as account_code2
, acc2.account_name as account_name2
, acc3.account_seq as account_seq3
, acc3.account_code as account_code3
, acc3.account_name as account_name3
, coalesce(mrd.amount, 0) as amount
, coalesce(mrd.amount_vat, 0) as amount_vat
FROM fim_money_requests mr
LEFT JOIN (select mrd.money_req_seq, mrd.bgm_proj_oper_exp_seq
	, sum(coalesce(mrd.amount, 0)) as amount
	, sum(coalesce(mrd.amount_vat, 0)) as amount_vat
	from fim_money_request_dtls mrd
	where mrd.record_status not like 'D'
	group by mrd.money_req_seq, mrd.bgm_proj_oper_exp_seq
) mrd ON mr.money_req_seq = mrd.money_req_seq
LEFT JOIN bgm_project_operation_expense pjexp ON mrd.bgm_proj_oper_exp_seq = pjexp.bgm_proj_oper_exp_seq
LEFT JOIN bgm_project_expense recexp ON pjexp.bgm_proj_exp_seq = recexp.bgm_proj_exp_seq
LEFT JOIN bgm_mas_expense exp ON recexp.bgm_exp_seq = exp.bgm_exp_seq
LEFT JOIN acm_mas_account acc1 ON exp.account_seq = acc1.account_seq
cross join acm_mas_base_account ba
LEFT JOIN acm_mas_account acc2 ON ba.suspense_input_tax_account_seq = acc2.account_seq
LEFT JOIN acm_mas_account acc3 ON ba.remain_account_seq = acc3.account_seq
WHERE mr.money_req_seq = @ref_seq
";
                                    dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                                    strSQL = @"
Insert into acm_transection_dtls
(tran_seq, account_seq, dr_or_cr, amount, record_status, created_by, created_when)
values
(@tran_seq, @account_seq, @dr_or_cr, @amount, @record_status, @created_by, @created_when);
";

                                    foreach (DataRow dr in dtb.Rows)
                                    {
                                        dbManager.CreateParameters(7);
                                        dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                        dbManager.AddParameters(1, "@account_seq", dr["account_seq1"].ToString());
                                        dbManager.AddParameters(2, "@dr_or_cr", "Dr");
                                        dbManager.AddParameters(3, "@amount", (main.ConvertNullDouble(dr["amount"]) ?? 0) - (main.ConvertNullDouble(dr["amount_vat"]) ?? 0));
                                        dbManager.AddParameters(4, "@record_status", "W");
                                        dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                        dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                                        if ((main.ConvertNullDouble(dr["amount_vat"]) ?? 0) != 0)
                                        {
                                            dbManager.CreateParameters(7);
                                            dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                            dbManager.AddParameters(1, "@account_seq", dr["account_seq2"].ToString());
                                            dbManager.AddParameters(2, "@dr_or_cr", "Dr");
                                            dbManager.AddParameters(3, "@amount", (main.ConvertNullDouble(dr["amount_vat"]) ?? 0));
                                            dbManager.AddParameters(4, "@record_status", "W");
                                            dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                            dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                            dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                                        }

                                        dbManager.CreateParameters(7);
                                        dbManager.AddParameters(0, "@tran_seq", strTranSeq);
                                        dbManager.AddParameters(1, "@account_seq", dr["account_seq3"].ToString());
                                        dbManager.AddParameters(2, "@dr_or_cr", "Cr");
                                        dbManager.AddParameters(3, "@amount", main.ConvertNullDouble(dr["amount"]) ?? 0);
                                        dbManager.AddParameters(4, "@record_status", "W");
                                        dbManager.AddParameters(5, "@created_by", nEmpSeqLogin);
                                        dbManager.AddParameters(6, "@created_when", DateTime.Now);
                                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                                    }

                                    break;
                                #endregion
                            }
                        }
                        #endregion
                        //========================================================================================================

                        dbManager.CommitTransaction();
                    }
                    catch (Exception ex)
                    {
                        dbManager.RollBackTransaction();
                        string errorStr = ex.Message + " " + ex.InnerException;
                        if (!directApprove) new Main().MessageAlert(Page, errorStr);
                        return errorStr;
                    }
                    finally
                    {
                        dbManager.Dispose();
                    }
                    #endregion
                    break;
                case "F":
                    mrInfo.bgm_proj_oper_seq = Convert.ToInt32(strMoneyReqSeq);
                    mrInfo.record_status = "P";
                    mrInfo.updated_by = nFromEmpSeq;
                    mrInfo.updated_when = DateTime.Now;
                    if (!mr.ChangeStatus(mrInfo))
                    {
                        string errorStr = "ไม่สามารถส่งต่อได้ เนื่องจากจำนวนเงินเกินกว่าที่ได้รับจัดสรร";
                        if (!directApprove) main.MessageAlert(Page, errorStr);
                        return errorStr;
                    }

                    info.send_date = DateTime.Today;
                    info.ref_seq = main.ConvertNullInt(strMoneyReqSeq);
                    info.ref_type = "fim_money_requests";
                    info.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text)); ;
                    info.send_text = "ส่งคำขอเบิกเงิน/ยืมเงิน : " + lblMoneyReqName.Text;
                    info.from_emp_seq = nFromEmpSeq;
                    info.from_pos_seq = nFromPosSeq;

                    if (PanelSendTo.Visible)
                    {
                        info.to_emp_seq = main.ConvertNullInt(strToEmpSeq);
                        info.to_pos_seq = nToPosSeq;//send.GetPosSeqFromEmpSeq(strToEmpSeq);
                    }
                    else if (PanelSendTo2.Visible)
                    {
                        info.pos_grp_seq = main.ConvertNullInt(lblPosGrpSeq.Text);
                    }

                    info.from_send_seq = main.ConvertNullInt(lblSendSeq.Text);
                    info.remarks = txtRemark.Text;
                    info.message_status = "0";
                    info.approve_path_seq = main.ConvertNullInt(lblNewApprovePathSeq.Text);
                    info.created_by = nEmpSeqLogin;
                    info.created_when = DateTime.Now;

                    if (main.CheckDuplicateMessage(lblSendSeq.Text))
                    {
                        main.MessageAlert(Page, "รายการนี้ส่งไปแล้ว กรุณาอย่ากดซ้ำ");
                        return "";
                    }

                    send.Insert(info);

                    info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                    info.message_status = "2";
                    info.wod_emp_seq = nWodEmpSeq;
                    info.updated_by = nEmpSeqLogin;
                    info.updated_when = DateTime.Now;
                    send.UpdateMessageStatus(info);
                    break;
                case "B":
                    mrInfo.money_req_seq = Convert.ToInt32(strMoneyReqSeq);
                    mrInfo.record_status = "R";
                    mrInfo.updated_by = nEmpSeqLogin;
                    mrInfo.updated_when = DateTime.Now;
                    mr.ChangeStatus(mrInfo);

                    info.send_date = DateTime.Today;
                    info.ref_seq = main.ConvertNullInt(strMoneyReqSeq);
                    info.ref_type = "return";
                    info.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                    info.send_text = "ส่งกลับเพื่อแก้ไข : " + lblMoneyReqName.Text;
                    info.from_emp_seq = nFromEmpSeq;
                    info.from_pos_seq = nFromPosSeq;
                    info.to_emp_seq = nToEmpSeq;
                    info.to_pos_seq = nToPosSeq;
                    info.from_send_seq = main.ConvertNullInt(lblSendSeq.Text);
                    info.remarks = txtRemark.Text;
                    info.message_status = "0";
                    info.approve_path_seq = null;//main.ConvertNullInt(lblNewApprovePathSeq.Text);
                    info.created_by = nEmpSeqLogin;
                    info.created_when = DateTime.Now;
                    send.Insert(info);

                    replyInfo.reply_date = DateTime.Today;
                    replyInfo.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text)); ;
                    replyInfo.reply_type = "0";
                    replyInfo.reply_text = "ส่งกลับมาเพื่อแก้ไข : " + lblMoneyReqName.Text;
                    replyInfo.from_emp_seq = nFromEmpSeq;
                    replyInfo.from_pos_seq = nFromPosSeq;
                    replyInfo.to_emp_seq = nToEmpSeq;
                    replyInfo.to_pos_seq = nToPosSeq;
                    replyInfo.wod_emp_seq = nWodEmpSeq;
                    replyInfo.from_send_seq = Convert.ToInt32(lblSendSeq.Text);
                    replyInfo.remarks = txtRemark.Text;
                    replyInfo.message_status = "0";
                    replyInfo.created_by = nEmpSeqLogin;
                    replyInfo.created_when = DateTime.Now;
                    reply.Insert(replyInfo);

                    info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                    info.message_status = "2";
                    info.wod_emp_seq = nWodEmpSeq;
                    info.updated_by = nEmpSeqLogin;
                    info.updated_when = DateTime.Now;
                    send.UpdateMessageStatus(info);
                    break;
            }

            if (rblUseAdvance.SelectedValue == "1")
            {
                //string strPaySeq = "";
                //FIM_Payments.M_FIM_Payments payInfo = pay.GetInfoFromMoneyReqSeq(strMoneyReqSeq);

                //if (payInfo.record_status == null)
                //{
                //    payInfo = new FIM_Payments.M_FIM_Payments();
                //    FIM_PaymentCheques.M_FIM_PaymentCheques payChequeInfo = new FIM_PaymentCheques.M_FIM_PaymentCheques();

                //    payInfo.bgm_source_seq = Convert.ToInt32(lblBgmSourceSeq.Text);
                //    payInfo.work_area_seq = Convert.ToInt32("1");
                //    payInfo.bgm_year = Convert.ToInt32(lblBgmYear.Text);
                //    payInfo.event_seq = main.ConvertNullInt(lblEventSeq.Text);
                //    payInfo.pay_name = "จ่าย" + lblMoneyReqName.Text;
                //    payInfo.ref_no = null;
                //    payInfo.pay_date = DateTime.Today;
                //    payInfo.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
                //    payInfo.emp_seq = main.ConvertNullInt(strFromEmpSeq);
                //    payInfo.contact_seq = null;
                //    payInfo.contact_person_seq = null;
                //    payInfo.petition_seq = null;
                //    payInfo.petition_dtls_seq = null;
                //    payInfo.amount = main.ConvertNullDouble(lblFinSumAmount.Text);
                //    payInfo.method_seq = 2;

                //    payInfo.created_by = nEmpSeqLogin;
                //    payInfo.created_when = DateTime.Now;

                //    strPaySeq = pay.Insert(payInfo);

                //    payChequeInfo.pay_seq = main.ConvertNullInt(strPaySeq);
                //    payChequeInfo.cheque_seq = main.ConvertNullInt(ddlCheque.SelectedValue);
                //    payChequeInfo.amount = main.ConvertNullDouble(lblFinSumAmount.Text);
                //    payChequeInfo.record_status = "W";
                //    payChequeInfo.created_by = nFromEmpSeq;
                //    payChequeInfo.created_when = DateTime.Now;

                //    payCheque.Insert(payChequeInfo);
                //}
                //else
                //{
                //    strPaySeq = lblPaySeq.Text;
                //    IList<FIM_PaymentCheques.M_FIM_PaymentCheques> infoList = payCheque.GetFull(strPaySeq, null);

                //    if (infoList.Count > 0)
                //    {
                //        FIM_PaymentCheques.M_FIM_PaymentCheques payChequeInfo2 = infoList[0];

                //        payChequeInfo2.pay_seq = main.ConvertNullInt(strPaySeq);
                //        payChequeInfo2.cheque_seq = main.ConvertNullInt(ddlCheque.SelectedValue);
                //        payChequeInfo2.amount = main.ConvertNullDouble(lblFinSumAmount.Text);
                //        payChequeInfo2.record_status = "W";
                //        payChequeInfo2.updated_by = nEmpSeqLogin;
                //        payChequeInfo2.updated_when = DateTime.Now;

                //        payCheque.Update(payChequeInfo2);
                //    }
                //}
            }

            if (directApprove)
            {
                directApprove = false;
            }
            else
            {
                ((TaskListsPopUp)Page).cmdViewRequest_Click(null, null);
            }
            return "";
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendTo2.Visible = false;
            PanelSendBack.Visible = false;
            // button
            PanelOption.Visible = true;
            PanelSend.Visible = false;
        }

        protected void ddlApprover_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal)ddlApprover.Footer.FindControl("RadComboItemsCount")).Text = Convert.ToString(ddlApprover.Items.Count);
        }

        protected void ddlApprover_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlApprover.DataSource = emplist.ListEmployeeByType("('1', '2', '3')", "");
            ddlApprover.DataBind();
        }

        protected void ddlApprover_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((DataRowView)e.Item.DataItem)["full_name"].ToString();
            e.Item.Value = ((DataRowView)e.Item.DataItem)["sequence"].ToString();
        }

        protected void ddlApprover_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadEmpInfo(ddlApprover.SelectedValue, null);
        }

        protected void LoadFinMoneyReqDtls()
        {
            double dSumAmount = 0;
            double dSumAmount1 = 0;
            double dSumAmount2 = 0;
            double dSumAmountTax = 0;
            double dSumAmountTax1 = 0;
            double dSumAmountTax2 = 0;
            double dSumAmountVat = 0;
            double dSumAmountVat1 = 0;
            double dSumAmountVat2 = 0;
            int nOldBgmExpSeq1 = 0;
            int nOldBgmExpSeq2 = 0;
            IList<FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls> masterListInfo
                = mrd.GetFull(lblMoneyReqSeq.Text).OrderBy(m => m.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.bgm_exp_seq).ToList();

            DataTable dtbExp2 = new DataTable();
            dtbExp2.Columns.Add("bgm_exp_seq", typeof(Int32));
            dtbExp2.Columns.Add("bgm_exp_name", typeof(String));
            dtbExp2.Columns.Add("amount", typeof(Double));
            dtbExp2.Columns.Add("amount_vat", typeof(Double));
            dtbExp2.Columns.Add("amount_tax", typeof(Double));

            DataTable dtbExp1 = new DataTable();
            dtbExp1.Columns.Add("upper_bgm_exp_seq", typeof(Int32));
            dtbExp1.Columns.Add("bgm_exp_seq", typeof(Int32));
            dtbExp1.Columns.Add("bgm_exp_name", typeof(String));
            dtbExp1.Columns.Add("amount", typeof(Double));
            dtbExp1.Columns.Add("amount_vat", typeof(Double));
            dtbExp1.Columns.Add("amount_tax", typeof(Double));

            DataTable dtbExp = new DataTable();
            dtbExp.Columns.Add("upper_bgm_exp_seq", typeof(Int32));
            dtbExp.Columns.Add("bgm_exp_seq", typeof(Int32));
            dtbExp.Columns.Add("bgm_exp_name", typeof(String));
            dtbExp.Columns.Add("remarks", typeof(String));
            dtbExp.Columns.Add("amount", typeof(Double));
            dtbExp.Columns.Add("amount_vat", typeof(Double));
            dtbExp.Columns.Add("amount_tax", typeof(Double));

            for (int i = 0; i < masterListInfo.Count; i++)
            {
                FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls info = masterListInfo[i];
                DataRow dr = dtbExp.NewRow();
                double dAmount = info.amount ?? 0;
                double dAmountVat = info.amount_vat ?? 0;
                double dAmountTax = info.amount_tax ?? 0;

                if (dAmount > 0)
                {
                    dr["upper_bgm_exp_seq"] = info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.bgm_exp_seq;
                    dr["bgm_exp_seq"] = info.m_bgm_projectoperationexpense.m_bgm_projectexpense.bgm_exp_seq;
                    dr["bgm_exp_name"] = info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_name;
                    dr["remarks"] = info.remarks;
                    dr["amount"] = dAmount;
                    dr["amount_vat"] = dAmountVat;
                    dr["amount_tax"] = dAmountTax;
                    dtbExp.Rows.Add(dr);
                    dSumAmount += dAmount;
                    dSumAmountVat += dAmountVat;
                    dSumAmountTax += dAmountTax;
                    // exp1 ======================================================================================
                    if (info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.bgm_exp_seq == nOldBgmExpSeq1)
                    {
                        dSumAmount1 += dAmount;
                        dSumAmountVat1 += dAmountVat;
                        dSumAmountTax1 += dAmountTax;
                    }
                    else
                    {
                        DataRow dr1 = dtbExp1.NewRow();
                        dr1["upper_bgm_exp_seq"] = info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.m_bgm_mas_expense_upper.bgm_exp_seq;
                        dr1["bgm_exp_seq"] = info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.bgm_exp_seq;
                        dr1["bgm_exp_name"] = info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.bgm_exp_name;

                        if (dtbExp1.Rows.Count > 0)
                        {
                            dtbExp1.Rows[dtbExp1.Rows.Count - 1]["amount"] = dSumAmount1;
                            dtbExp1.Rows[dtbExp1.Rows.Count - 1]["amount_vat"] = dSumAmountVat1;
                            dtbExp1.Rows[dtbExp1.Rows.Count - 1]["amount_tax"] = dSumAmountTax1;
                        }

                        dSumAmount1 = dAmount;
                        dSumAmountVat1 = dAmountVat;
                        dSumAmountTax1 = dAmountTax;
                        nOldBgmExpSeq1 = info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.bgm_exp_seq.Value;

                        dtbExp1.Rows.Add(dr1);
                    }
                    // exp2 ======================================================================================
                    if (info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.m_bgm_mas_expense_upper.bgm_exp_seq == nOldBgmExpSeq2)
                    {
                        dSumAmount2 += dAmount;
                        dSumAmountVat2 += dAmountVat;
                        dSumAmountTax2 += dAmountTax;
                    }
                    else
                    {
                        DataRow dr2 = dtbExp2.NewRow();
                        dr2["bgm_exp_seq"] = info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.m_bgm_mas_expense_upper.bgm_exp_seq;
                        dr2["bgm_exp_name"] = info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.m_bgm_mas_expense_upper.bgm_exp_name;

                        if (dtbExp2.Rows.Count > 0)
                        {
                            dtbExp2.Rows[dtbExp2.Rows.Count - 1]["amount"] = dSumAmount2;
                            dtbExp2.Rows[dtbExp2.Rows.Count - 1]["amount_vat"] = dSumAmountVat2;
                            dtbExp2.Rows[dtbExp2.Rows.Count - 1]["amount_tax"] = dSumAmountTax2;
                        }

                        dSumAmount2 = dAmount;
                        dSumAmountVat2 = dAmountVat;
                        dSumAmountTax2 = dAmountTax;
                        nOldBgmExpSeq2 = info.m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.m_bgm_mas_expense_upper.bgm_exp_seq.Value;

                        dtbExp2.Rows.Add(dr2);
                    }
                }

                if (i == masterListInfo.Count - 1 && dtbExp2.Rows.Count > 0)
                {
                    dtbExp2.Rows[dtbExp2.Rows.Count - 1]["amount"] = dSumAmount2;
                    dtbExp2.Rows[dtbExp2.Rows.Count - 1]["amount_vat"] = dSumAmountVat2;
                    dtbExp2.Rows[dtbExp2.Rows.Count - 1]["amount_tax"] = dSumAmountTax2;
                    dtbExp1.Rows[dtbExp1.Rows.Count - 1]["amount"] = dSumAmount1;
                    dtbExp1.Rows[dtbExp1.Rows.Count - 1]["amount_vat"] = dSumAmountVat1;
                    dtbExp1.Rows[dtbExp1.Rows.Count - 1]["amount_tax"] = dSumAmountTax1;
                }
            }

            RepeaterBgmExp2.DataSource = dtbExp2;
            RepeaterBgmExp2.DataBind();

            for (int k = 0; k < RepeaterBgmExp2.Items.Count; k++)
            {
                Repeater RepeaterBgmExp1 = (Repeater)RepeaterBgmExp2.Items[k].FindControl("RepeaterBgmExp1");
                Label lblBgmExpSeq = (Label)RepeaterBgmExp2.Items[k].FindControl("lblBgmExpSeq");

                DataTable dtbExp1Copy = dtbExp1.Copy();
                dtbExp1Copy.Rows.Clear();
                DataRow[] drc3 = dtbExp1.Select("upper_bgm_exp_seq = " + lblBgmExpSeq.Text);
                foreach (DataRow dr in drc3)
                {
                    DataRow drCopy = dr;
                    dtbExp1Copy.ImportRow(drCopy);
                }

                RepeaterBgmExp1.DataSource = dtbExp1Copy;
                RepeaterBgmExp1.DataBind();

                for (int m = 0; m < RepeaterBgmExp1.Items.Count; m++)
                {
                    Repeater RepeaterBgmExp = (Repeater)RepeaterBgmExp1.Items[m].FindControl("RepeaterBgmExp");
                    Label lblBgmExpSeq2 = (Label)RepeaterBgmExp1.Items[m].FindControl("lblBgmExpSeq");

                    DataTable dtbExpCopy = dtbExp.Copy();
                    dtbExpCopy.Rows.Clear();
                    DataRow[] drc4 = dtbExp.Select("upper_bgm_exp_seq = " + lblBgmExpSeq2.Text);
                    foreach (DataRow dr in drc4)
                    {
                        DataRow drCopy = dr;
                        dtbExpCopy.ImportRow(drCopy);
                    }

                    RepeaterBgmExp.DataSource = dtbExpCopy;
                    RepeaterBgmExp.DataBind();
                }
            }

            lblFinSumAmount.Text = dSumAmount.ToString("#,###.00");
            lblFinSumAmountVat.Text = dSumAmountVat.ToString("#,###.00");
            lblFinSumAmountTax.Text = dSumAmountTax.ToString("#,###.00");
        }

        protected void SetEditBgmSource(bool bEdit)
        {
            cmdEditBgmSource.Visible = !bEdit;
            cmdUpdateBgmSource.Visible = bEdit;
            cmdCancelBgmSource.Visible = bEdit;
            lblBgmSourceName.Visible = !bEdit;
            rblUseAdvance.Visible = bEdit;
        }

        protected void cmdEditBgmSource_Click(object sender, EventArgs e)
        {
            SetEditBgmSource(true);
        }

        protected void cmdUpdateBgmSource_Click(object sender, EventArgs e)
        {
            HttpCookie cookie = new HttpCookie("UserDetail");
            string strRemarks = lblRemarks.Text + (lblRemarks.Text.Length > 0 ? "<br />" : "") + "แก้ไขโดย " + Session["UserName"].ToString() + " เมื่อ " + DateTime.Now.ToShortDateString();

            mr.UpdateUseAdvance(lblMoneyReqSeq.Text, rblUseAdvance.SelectedValue, strRemarks, Session["EmpSeq"].ToString());
            lblBgmSourceName.Text = rblUseAdvance.SelectedItem.Text;
            lblRemarks.Text = strRemarks;
            SetEditBgmSource(false);

            //PanelPayment.Visible = rblUseAdvance.SelectedValue == "1";
            //LoadDDLBankAccSeq(lblBgmSourceSeq.Text);
            //LoadDDLChequeBook();
            //LoadDDLCheque();
        }

        protected void cmdCancelBgmSource_Click(object sender, EventArgs e)
        {
            SetEditBgmSource(false);
        }

        protected void ddlBankAccSeq_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDDLChequeBook();
        }

        protected void ddlChequeBook_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDDLCheque();
        }

        protected void LoadRepeaterAccount()
        {
            if (lblEventSeq.Text == "11")
            {
                DataTable dtb = acc.GetDeliveryNoteInfo(lblDnSeq.Text);

                if (dtb.Rows.Count > 0)
                {
                    lblTranName1.Text = main.ConvertNullDateTime(dtb.Rows[0]["ReceiveDate"]).Value.ToShortDateString() + " - [" + dtb.Rows[0]["Code"].ToString() + "] " + dtb.Rows[0]["Name"].ToString();
                    var list = acc.GetListDetail(main.ConvertNullInt(lblDnSeq.Text), "icm_delivery_note");

                    double dAmountDr = main.ConvertNullDouble(list.Sum(m => m.amount_dr)) ?? 0;
                    double dAmountCr = main.ConvertNullDouble(list.Sum(m => m.amount_cr)) ?? 0;

                    list.Add(new DAL.M_ACM_GENERATE_ACCOUNT_Auto() { account_name = "รวม", amount_dr = dAmountDr, amount_cr = dAmountCr });
                    RepeaterAccount1.DataSource = list;
                    RepeaterAccount1.DataBind();
                    ul1.Visible = true;
                }
            }

            lblTranName2.Text = lblMoneyReqDate.Text + " - [" + lblMoneyReqRefNo.Text + "] " + lblMoneyReqName.Text;
            var list2 = acc.GetListDetail(main.ConvertNullInt(lblMoneyReqSeq.Text), "fim_money_requests");

            double dAmountDr2 = main.ConvertNullDouble(list2.Sum(m => m.amount_dr)) ?? 0;
            double dAmountCr2 = main.ConvertNullDouble(list2.Sum(m => m.amount_cr)) ?? 0;

            list2.Add(new DAL.M_ACM_GENERATE_ACCOUNT_Auto() { account_name = "รวม", amount_dr = dAmountDr2, amount_cr = dAmountCr2 });
            RepeaterAccount2.DataSource = list2;
            RepeaterAccount2.DataBind();
        }
    }
}